/**
 * 
 */
package com.fr.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fr.model.Person;
import com.fr.service.FaceServiceDAO;
import com.fr.util.ParseJson;
import com.fr.util.SetSecretKey;
import com.fr.util.WriteResult;
import com.youtu.sign.Base64Util;

/**
 * @author 作者：Zhangyangyang
 * @version 创建时间：2017年1月4日 下午1:10:49 类说明：前台请求处理类
 */
@Controller
public class FaceRecongitionConroller {
	@Autowired
	private FaceServiceDAO faceServiceDAO;
	private static int FORMATCODE = -2001;
	private static String FORMATMESSAGE = "ERROR-JSON-FORMAT";

	// 请求签名
	@RequestMapping(value = "getSign", method = RequestMethod.GET)
	public void getSign(HttpServletRequest request, HttpServletResponse response) throws IOException, JSONException {
		// 签名时间要制定一个规则(失效时间，这个以后再说)
		String sign = faceServiceDAO.getSign(); // 定义sign用来存放签名
												// 定义返回数据
		JSONObject newData = new JSONObject();
		JSONObject json = new JSONObject();
		json.put("flag", true);
		json.put("sign", sign); // 签名字符串
		newData.put("data", json);
		WriteResult.backJson(newData.toString(), request, response);
	}

	// 添加用户
	@RequestMapping(value = "addPerson", method = RequestMethod.POST)
	@ResponseBody
	public void addPerson(@RequestBody String data, HttpServletRequest request, HttpServletResponse response)
			throws IOException, JSONException {

		Map<String, Object> backmap = new HashMap<>(); // 定义返回数据
		String[] str = { "person_name", "image", "group_id" }; // 定义json数据中的参数名称
		Map<String, Object> map = ParseJson.otherDo(data, str); // 检测json数据格式
		if ((boolean) map.get("flag")) {
			String person_name = map.get("person_name").toString();
			String image = map.get("image").toString();
			String person_id = "person" + SetSecretKey.generateString();
			String group_id = map.get("group_id").toString();
			Person person = new Person(person_name, person_id, group_id); // 创建person对象
			backmap = faceServiceDAO.addPerson(person, image); // 添加用户操作
		} else { // josn格式错误
			JSONObject json = new JSONObject();
			json.put("code", FORMATCODE); // 返回码
			json.put("data", new JSONObject());
			json.put("message", FORMATMESSAGE);
			backmap.put("json", json);
		}
		WriteResult.backJson(backmap.get("json").toString(), request, response);
	}

	// 添加人脸
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "addFace", method = RequestMethod.POST)
	@ResponseBody
	public void addFace(@RequestBody String data, HttpServletRequest request, HttpServletResponse response)
			throws IOException, JSONException {

		Map<String, Object> backmap = new HashMap<>(); // 定义返回数据
		Map<String, Object> map = ParseJson.addPicDo(data); // json数据检测
		if ((boolean) map.get("flag")) {
			String person_name = map.get("person_name").toString();
			List<String> images = (List<String>) map.get("list");
			backmap = faceServiceDAO.addFace(person_name, images); // 添加人脸操作
		} else { // josn格式错误
			JSONObject json = new JSONObject();
			json.put("code", FORMATCODE);
			json.put("data", new JSONObject());
			json.put("message", FORMATMESSAGE);
			backmap.put("json", json);
		}
		WriteResult.backJson(backmap.get("json").toString(), request, response);
	}

	// 获得所有组列表
	@RequestMapping(value = "getAllGroup", method = RequestMethod.GET)
	public void getAllGroup(HttpServletRequest request, HttpServletResponse response)
			throws IOException, JSONException {
		Map<String, Object> map = faceServiceDAO.findGroupAll(); // 获得全部分组
		JSONObject newData = new JSONObject();
		JSONObject json = new JSONObject();
		json.put("flag", map.get("flag"));
		json.put("json", map.get("message"));
		newData.put("data", json);
		WriteResult.backJson(newData.toString(), request, response);
	}

	// 删除人脸
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "deleteFace", method = RequestMethod.POST)
	@ResponseBody
	public void deleteFace(@RequestBody String data, HttpServletRequest request, HttpServletResponse response)
			throws IOException, JSONException {

		Map<String, Object> backmap = new HashMap<>(); // 定义返回数据
		Map<String, Object> map = ParseJson.addPicDo(data); // json数据检测
		if ((boolean) map.get("flag")) {
			String person_name = map.get("person_name").toString();
			List<String> list = (List<String>) map.get("list");
			backmap = faceServiceDAO.deleteFace(person_name, list); // 删除人脸操作
		} else {
			JSONObject json = new JSONObject(); // josn格式错误
			json.put("code", FORMATCODE);
			json.put("data", new JSONObject());
			json.put("message", FORMATMESSAGE);
			backmap.put("json", json);
		}

		WriteResult.backJson(backmap.get("json").toString(), request, response);

	}

	// 删除person
	@ResponseBody
	@RequestMapping(value = "deletePerson", method = RequestMethod.POST)
	public void deletePerson(@RequestBody String data, HttpServletRequest request, HttpServletResponse response)
			throws IOException, JSONException {

		Map<String, Object> backmap = new HashMap<>(); // 定义返回数据
		String[] str = { "person_id" };
		Map<String, Object> map = ParseJson.otherDo(data, str);
		if ((boolean) map.get("flag")) {
			String person_id = map.get("person_id").toString();
			backmap = faceServiceDAO.deletePerson(person_id);
		} else {
			// josn格式错误
			JSONObject json = new JSONObject();
			json.put("code", FORMATCODE);
			json.put("data", new JSONObject());
			json.put("message", FORMATMESSAGE);
			backmap.put("json", json);
		}

		WriteResult.backJson(backmap.get("json").toString(), request, response);

	}

	// 查询person信息
	@RequestMapping(value = "findPerson", method = RequestMethod.POST)
	@ResponseBody
	public void findPerson(@RequestBody String data, HttpServletRequest request, HttpServletResponse response)
			throws IOException, JSONException {
		// 定义返回数据
		Map<String, Object> backmap = new HashMap<>();
		String[] str = { "person_id" };
		Map<String, Object> map = ParseJson.otherDo(data, str);
		if ((boolean) map.get("flag")) {
			String person_id = map.get("person_id").toString();
			backmap = faceServiceDAO.findPersonByPersonId(person_id);
		} else {
			// josn格式错误
			JSONObject json = new JSONObject();
			json.put("code", FORMATCODE);
			json.put("data", new JSONObject());
			json.put("message", FORMATMESSAGE);
			backmap.put("json", json);
		}
		WriteResult.backJson(backmap.get("json").toString(), request, response);
	}

	// 查询所有person信息
	@RequestMapping(value = "findAllPerson", method = RequestMethod.POST)
	public void findAllPerson(@RequestBody String data, HttpServletRequest request, HttpServletResponse response)
			throws IOException, JSONException {
		Map<String, Object> backmap = new HashMap<>();
		String[] str = { "group_id" };
		Map<String, Object> map = ParseJson.otherDo(data, str);
		if ((boolean) map.get("flag")) {
			String group_id = map.get("group_id").toString();
			// List<Object> list = faceServiceDAO.findPersonByGroupId(group_id);
			backmap = faceServiceDAO.findPersonsByGroupId(group_id);
		} else {
			// josn格式错误
			JSONObject json = new JSONObject();
			json.put("code", FORMATCODE);
			json.put("data", new JSONObject());
			json.put("message", FORMATMESSAGE);
			backmap.put("json", json);
		}
		WriteResult.backJson(backmap.get("json").toString(), request, response);
	}

	// 修改person的name
	@RequestMapping(value = "changePerName", method = RequestMethod.POST)
	@ResponseBody
	public void changePerName(@RequestBody String data, HttpServletRequest request, HttpServletResponse response)
			throws IOException, JSONException {
		// 定义返回数据
		Map<String, Object> backmap = new HashMap<>();
		String[] str = { "person_name", "new_name" };
		Map<String, Object> map = ParseJson.otherDo(data, str);
		if ((boolean) map.get("flag")) {
			String person_name = map.get("person_name").toString();
			String new_name = map.get("new_name").toString();
			backmap = faceServiceDAO.updatePerson(person_name, new_name);
		} else {
			// josn格式错误
			JSONObject json = new JSONObject();
			json.put("code", FORMATCODE);
			json.put("data", new JSONObject());
			json.put("message", FORMATMESSAGE);
			backmap.put("json", json);
		}
		WriteResult.backJson(backmap.get("json").toString(), request, response);
	}

	// 人脸检索
	@RequestMapping(value = "FaceIdentify", method = RequestMethod.POST)
	@ResponseBody
	public void FaceIdentify(@RequestBody String data, HttpServletRequest request, HttpServletResponse response)
			throws IOException, JSONException {

		// 定义返回数据
		Map<String, Object> backmap = new HashMap<>();
		String[] str = { "image", "group_id" };
		Map<String, Object> map = ParseJson.otherDo(data, str);
		if ((boolean) map.get("flag")) {
			String image = map.get("image").toString();
			String group_id = map.get("group_id").toString();
			backmap = faceServiceDAO.faceRecongition(image, group_id);
		} else {
			// josn格式错误
			JSONObject json = new JSONObject();
			json.put("code", FORMATCODE);
			json.put("d	ata", new JSONObject());
			json.put("message", FORMATMESSAGE);
			backmap.put("json", json);
		}
		WriteResult.backJson(backmap.get("json").toString(), request, response);

	}

	// 人脸检测
	@RequestMapping(value = "FaceDetect", method = RequestMethod.POST)
	@ResponseBody
	public void FaceDetect(@RequestBody String data, HttpServletRequest request, HttpServletResponse response)
			throws IOException, JSONException {
		// 定义返回数据
		Map<String, Object> backmap = new HashMap<>();
		Map<String, Object> map = ParseJson.addPicOne(data);
		if ((boolean) map.get("flag")) {
			String image = map.get("image").toString();
			int mode = Integer.valueOf(map.get("mode").toString());
			backmap = faceServiceDAO.faceDetect(image, mode);
		} else {
			// josn格式错误
			JSONObject json = new JSONObject();
			json.put("code", FORMATCODE);
			json.put("data", new JSONObject());
			json.put("message", FORMATMESSAGE);
			backmap.put("json", json);
		}
		WriteResult.backJson(backmap.get("json").toString(), request, response);

	}

	// 人脸检测&检索
	@RequestMapping(value = "FaceDetIdentify", method = RequestMethod.POST)
	@ResponseBody
	public void FaceDetIdentify(@RequestBody String data, HttpServletRequest request, HttpServletResponse response)
			throws IOException, JSONException {
		// 定义返回数据
		Map<String, Object> backmap = new HashMap<>();
		String[] str = { "image", "group_id" };
		Map<String, Object> map = ParseJson.otherDo(data, str);
		if ((boolean) map.get("flag")) {
			String image = map.get("image").toString();
			String group_id = map.get("group_id").toString();
			backmap = faceServiceDAO.faceRecongition(image, group_id);
		} else {
			// josn格式错误
			JSONObject json = new JSONObject();
			json.put("code", FORMATCODE);
			json.put("data", new JSONObject());
			json.put("message", FORMATMESSAGE);
			backmap.put("json", json);
		}
		WriteResult.backJson(backmap.get("json").toString(), request, response);

	}

	/**
	 * 用来本地测试添加图片
	 */
	public String readFile(String filePath) throws IOException {
		File imageFile = new File(filePath);
		StringBuffer str = new StringBuffer("");
		if (imageFile.exists()) {
			InputStream in = new FileInputStream(imageFile);
			byte data[] = new byte[(int) imageFile.length()]; // 创建合适文件大小的数组
			in.read(data); // 读取文件中的内容到b[]数组
			in.close();
			str.append(Base64Util.encode(data));
		} else {
			throw new FileNotFoundException(filePath + " not exist");
		}
		return str.toString();
	}

}
